package com.asset.dispoal.business.approval.service.command;

import com.asset.dispoal.business.approval.domain.db.entity.RepaymentApprover;
import com.asset.dispoal.business.approval.domain.db.mapper.RepaymentApproverMapper;
import com.asset.dispoal.business.approval.dto.RepaymentApproverBindRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.Date;

/**
 * @description:
 * @author: yf
 * @date: 2022-10-09 10:10:33
 */
@Repository
public class BindReapymentApproverCommand implements BaseCommand<RepaymentApproverBindRequest, Result> {
    @Autowired
    private RepaymentApproverMapper repaymentApproverMapper;
    @Autowired
    private BaseIdeable<String> ideable;

    @Override
    @Transactional
    public Result execute(RepaymentApproverBindRequest request) {
        String assetInstBatchId = request.getAssetInstBatchId();
        RepaymentApprover repaymentApprover = repaymentApproverMapper.queryByassetInstBatchId(assetInstBatchId);
        repaymentApprover.setDeleted("1");
        int updateRes = repaymentApproverMapper.update(repaymentApprover);
        if (updateRes <= 0) {
            throw new BusinessException(400, "审核人绑定失败！！", "");
        }

        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        String userIds = String.join(",", request.getUserIds());
        RepaymentApprover approved = RepaymentApprover.builder()
                .id(ideable.generateId())
                .assetInstBatchId(assetInstBatchId)
                .approverIds(userIds)
                .createTime(new Date())
                .createUserId(userId)
                .deleted("0")
                .build();
        int insertRes = repaymentApproverMapper.insert(approved);
        if (insertRes <= 0) {
            throw new BusinessException(400, "审核人绑定失败！！", "");
        }
        return Result.ok();
    }
}
